<template>
  <div class="page-container page-footer-btn">
    <van-cell-group>
      <van-field v-model="form.warehouseName" label="仓库"  readonly />

      <van-field
        v-model="form.reagentTeamName"
        :disabled="strings.isNotBlank(form.id)"
        label="试剂专业组"
        is-link
        clearable
        placeholder="请选择专业组"
        @focus="open('ReagentTeam')"
      />
      <van-field
        v-model="form.matrName"
        :disabled="strings.isNotBlank(form.id)"
        label="试剂"
        is-link
        clearable
        placeholder="请选择试剂"
        @focus="open('Matr')"
      />
      <van-field
        v-model="form.checkTypeName"
        :disabled="strings.isNotBlank(form.id)"
        label="盘点类型"
        is-link
        clearable
        placeholder="请选择"
        @focus="open('checkType')"
      />

      <van-row>
        <van-col span="18">
          <FortenScan
            ref="scan"
            propPlaceholder="请扫描SN/RFID条码"
            propErrorMsg="请扫描正确的SN/RFID"
            :propTypeArr="['sn', 'rfid']"
            @scanCall="handleScanOver"
            :disabled="strings.isBlank(form.id) || form.flagFinished != 0"
          />
        </van-col>
        <van-col span="6">
          <van-button
            size="small"
            type="primary"
            @click="RFIDScn"
            :disabled="strings.isBlank(form.id) || form.flagFinished != 0"
            >扫描盘点</van-button
          >
        </van-col>
      </van-row>
    </van-cell-group>
    <van-row class="check-row">
      <van-col span="12"
        ><h4>单号： {{ strings.defaultString(form.busKey, '自动设置') }}</h4></van-col
      >
      <van-col span="12" style="padding-top: 9px">
        <van-field       is-link clearable placeholder="选择盘点单" @focus="open('stockCheck')" />
      </van-col>
    </van-row>
    <van-row class="check-row">
      <van-col span="6" style="color: #1989fa">理论库存</van-col>
      <van-col span="6" style="color: green">正常</van-col>
      <van-col span="6" style="color: red">盘盈</van-col>
      <van-col span="6" style="color: #ff8917">盘亏/未盘</van-col>
    </van-row>
    <van-row class="check-row">
      <van-col span="6" style="color: #1989fa">{{ form.stockNum }}</van-col>
      <van-col span="6" style="color: green">{{ form.stockNormal }}</van-col>
      <van-col span="6" style="color: red">{{ form.stockSurplus }}</van-col>
      <van-col span="6" style="color: #ff8917">{{ form.stockUnknown }}</van-col>
    </van-row>

    <van-tabs v-model="active" @change="activeChange">
      <van-tab title="盘盈/盘亏/未盘">
        <FortenList
          ref="listItem1"
          :propNoCheck="true"
          :propAutoFetchData="false"
                    propUrl="/wm/tertiary_stock_check_item/page"
                    @click="showStock"
        >
          <template #default="{ item }">
            <van-row :style="{ color: getCheckStatus(item.checkStatus).color }">
              <van-col span="3">试剂:</van-col>
              <van-col span="21">{{ item.matrName }}</van-col>
            </van-row>
            <van-row :style="{ color: getCheckStatus(item.checkStatus).color }">
              <van-col span="3">品规:</van-col>
              <van-col span="21">{{ item.matrSpec }}</van-col>
            </van-row>
            <van-row :style="{ color: getCheckStatus(item.checkStatus).color }">
              <van-col span="3">RFID:</van-col>
              <van-col span="10"> {{ item.rfid == null ? '无' : item.rfid }}</van-col>
              <van-col span="3">SN:</van-col>
              <van-col span="8">{{ item.sn }}</van-col>
            </van-row>
            <van-row :style="{ color: getCheckStatus(item.checkStatus).color }">
              <!-- <van-col span="3">库位:</van-col>
              <van-col span="15">{{item.locationName}}</van-col> -->
              <van-col span="3">状态:</van-col>
              <van-col span="3">{{ getCheckStatus(item.checkStatus).value }}</van-col>
            </van-row>
          </template>
        </FortenList>
      </van-tab>
      <van-tab title="正常">
        <FortenList
          ref="listItem2"
          :propNoCheck="true"
          :propAutoFetchData="false"
                    propUrl="/wm/tertiary_stock_check_item/page"
                    @click="showStock"
        >
          <template #default="{ item }">
            <van-row :style="{ color: getCheckStatus(item.checkStatus).color }">
              <van-col span="3">试剂:</van-col>
              <van-col span="21">{{ item.matrName }}</van-col>
            </van-row>
            <van-row :style="{ color: getCheckStatus(item.checkStatus).color }">
              <van-col span="3">品规:</van-col>
              <van-col span="21">{{ item.matrSpec }}</van-col>
            </van-row>
            <van-row :style="{ color: getCheckStatus(item.checkStatus).color }">
              <van-col span="3">RFID:</van-col>
              <van-col span="10"> {{ item.rfid == null ? '无' : item.rfid }}</van-col>
              <van-col span="3">SN:</van-col>
              <van-col span="8">{{ item.sn }}</van-col>
            </van-row>
            <van-row :style="{ color: getCheckStatus(item.checkStatus).color }">
              <!-- <van-col span="3">库位:</van-col>
              <van-col span="15">{{item.locationName}}</van-col> -->
              <van-col span="3">状态:</van-col>
              <van-col span="3">{{ getCheckStatus(item.checkStatus).value }}</van-col>
            </van-row>
          </template>
        </FortenList>
      </van-tab>
    </van-tabs>
    <van-action-sheet v-model="visible" :actions="resultActions" get-container="body" />
    <van-row type="flex" justify="space-around" class="footer-btn">
      <van-col span="8">
        <van-button type="primary"    @click="handleBegin" :disabled="strings.isNotBlank(form.id)">开始盘点</van-button>
      </van-col>
      <van-col span="8">
        <van-button type="danger" @click="handleEnd" :disabled="strings.isBlank(form.id) || form.flagFinished != 0"
          >结束盘点</van-button
        >
      </van-col>
    </van-row>

    <FortenList
      ref="listItemReagentTeam"
      :propAutoFetchData="false"
                :propIsRadio="true"
                :propFlagPopup="true"
                :propSearchFields="['name']"
                :propSearchTextAppend="'名称/编码'"
                propUrl="/base/reagent_team/list"
                @change="changeReagentTeam"
    >
      <template #default="{ item }">
        <van-row>
          <van-col span="4">
            <van-radio   :name="item"  />
          </van-col>
          <van-col span="4">名称：</van-col>
          <van-col span="16">{{ item.name }}</van-col>
        </van-row>
        <van-row>
          <van-col span="4"> </van-col>
          <van-col span="4">编码：</van-col>
          <van-col span="16">{{ item.code }}</van-col>
        </van-row>
      </template>
    </FortenList>

    <FortenList
      ref="listItemMatr"
      :propAutoFetchData="false"
                :propIsRadio="true"
                :propFlagPopup="true"
      :propSearchFields="['name', 'spec']"
                :propSearchTextAppend="'品名/品规'"
                propUrl="/base/matr/pageUsing"
                @change="changeMatr"
    >
      <template #default="{ item }">
        <van-row>
          <van-col span="4">
            <van-radio   :name="item"  />
          </van-col>
          <van-col span="4">品名：</van-col>
          <van-col span="14">{{ item.name }}</van-col>
        </van-row>
        <van-row>
          <van-col span="4"> </van-col>
          <van-col span="4">品规：</van-col>
          <van-col span="14">{{ item.spec }}</van-col>
        </van-row>
      </template>
    </FortenList>

    <FortenList
      ref="listItemStockCheck"
      :propAutoFetchData="false"
                :propIsRadio="true"
                :propFlagPopup="true"
                :propSearchFields="['name']"
                :propSearchTextAppend="'单号/试剂'"
                propUrl="/wm/tertiary_stock_check/page"
                @change="changeStockCheck"
    >
      <template #default="{ item }">
        <van-row>
          <van-col span="2">
            <van-radio   :name="item"  />
          </van-col>
          <van-col span="5">仓库：</van-col>
          <van-col span="17">{{ item.warehouseName }}</van-col>
        </van-row>
        <van-row>
          <van-col span="5">试剂组：</van-col>
          <van-col span="19">{{item.reagentTeamName}}</van-col>
        </van-row>
        <van-row>
          <van-col span="5">试剂：</van-col>
          <van-col span="19">{{ item.matrName }}</van-col>
        </van-row>
        <van-row>
          <van-col span="5">单号：</van-col>
          <van-col span="19">{{ item.busKey }}</van-col>
        </van-row>
        <van-row>
          <van-col span="5">时间：</van-col>
          <van-col span="19">{{ item.gmtCreate }}</van-col>
        </van-row>
      </template>
    </FortenList>

    <!-- 盘点类型选择-->
    <van-popup position="bottom" closeable v-model="selectVisible">
      <van-radio-group v-model="form.checkType" style="margin-top: 40px">
        <van-cell-group>
          <van-cell
            @click="selectChange(item)"
            v-for="item in checkTypeList"
            :key="item.value"
            :title="item.label"
            clickable
          >
            <template #right-icon>
              <van-radio :name="item.value" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
    </van-popup>
  </div>
</template>
<script>
import { Dialog } from 'vant'

export default {
  data() {
    return {
      scan: '',
      form: {},
      warehouseList: [],
      result: {
        matrName: '无',
        matrSpec: '无',
        locationName: '无',
        ready: '无',
        lost: '无'
      },
      visible: false,
      stocks: [],
      active: '1',
      showSheet: '',
      checkStatus: [
        { key: 0, value: '正常', color: 'green' },
        { key: 1, value: '盘盈', color: 'red' },
        { key: -1, value: '盘亏', color: '#ff8917' },
        { key: -9, value: '未盘', color: '#ff8917' },
      ],
      selectVisible: false,
      checkTypeList: [
        {
          value: 'all',
          label: '所有库存',
          remark: '所选试剂组的所有试剂库存',
          disabled: false
        },
        {
          value: 'today',
          label: '今天库存变动',
          remark: '所选试剂组今天的试剂变动库存',
          disabled: false
        },
        {
          value: 'yesterday',
          label: '昨天库存变动',
          remark: '所选试剂组昨天的试剂变动库存',
          disabled: false
        },
        {
          value: 'thisWeek',
          label: '本周库存变动',
          remark: '所选试剂组本周的试剂变动库存',
          disabled: false
        },
        {
          value: 'thisMonth',
          label: '本月库存变动',
          remark: '所选试剂组本月的试剂变动库存',
          disabled: false
        },
        {
          value: 'lastMonth',
          label: '上月库存变动',
          remark: '所选试剂组上月的试剂变动库存',
          disabled: false
        }
      ]
    }
  },
  props: {
    propFlowKey: String
  },
  components: {
  },
  computed: {
    resultActions() {
      let actions = [
        { name: `品名： ${this.result.matrName}` },
        { name: `品规： ${this.result.matrSpec}` },
        // {name: `库位： ${this.result.locationName}`},
        { name: `已盘： ${this.result.ready}` },
        { name: `未盘： ${this.result.lost}` },
      ]
      return actions
    }
  },
  methods: {
    RFIDScn() {
      //保存之后回调，只有有数据才会回调
      window.scanConfirm = (rfidList) => {
        this.utils.loadShow()
        let param = {
          ucList: rfidList,
          checkId: this.form.id,
        }
        this.$ajax.post('/wm/tertiary_stock_check/RFIDScan', param).then(resp => {
          if (resp.code == 0) {
            if (resp.msg.indexOf('正常') != -1) {
              this.$notify.success(resp.msg)
            } else {
              this.$notify.warning(resp.msg)
            }
            this.$set(this.form, 'stockNum', resp.data.stockNum)
            this.$set(this.form, 'stockNormal', resp.data.stockNormal)
            this.$set(this.form, 'stockSurplus', resp.data.stockSurplus)
            this.$set(this.form, 'stockUnknown', resp.data.stockUnknown)
            this.$set(this.form, 'stockLoss', resp.data.stockLoss)
            this.reloadList()
            this.utils.loadHide()
          }
        })
      }
      this.utilPrint.openRfidScan()
    },
    //扫描
    async handleScanOver(scanValue) {
      this.utils.loadShow()
      this.$ajax.get(`/wm/tertiary_stock_check/scan?uc=${scanValue}&checkId=${this.form.id}&isScan=1`).then(resp => {
        if (resp.code == 0) {
          if (resp.msg.indexOf('正常') != -1) {
            this.$notify.success(resp.msg)
          } else {
            this.$notify.warning(resp.msg)
          }
          this.$set(this.form, 'stockNum', resp.data.stockNum)
          this.$set(this.form, 'stockNormal', resp.data.stockNormal)
          this.$set(this.form, 'stockSurplus', resp.data.stockSurplus)
          this.$set(this.form, 'stockUnknown', resp.data.stockUnknown)
          this.$set(this.form, 'stockLoss', resp.data.stockLoss)
          this.reloadList()
          this.utils.loadHide()
        }
        this.utils.clearFocus(this, 'scan', 'scan')
      })
    },

    //切换tab
    activeChange() {
      setTimeout(() => {
        this.reloadList()
      }, 500)
    },

    //刷新列表
    reloadList() {
      try {
        let wrapper1 = this.$newWrapper().eq('checkId', this.form.id || -1).ne('checkStatus', '0')
        wrapper1.orderConditions.push({ field: 'gmtCreate', rule: 'desc' })
        this.$refs.listItem1.setQueryWrapper(wrapper1)
      } catch (_) { _ }
      try {
        let wrapper2 = this.$newWrapper().eq('checkId', this.form.id || -1).eq('checkStatus', '0')
        wrapper2.orderConditions.push({ field: 'gmtCreate', rule: 'desc' })
        this.$refs.listItem2.setQueryWrapper(wrapper2)
      } catch (_) { _ }
    },

    //开始盘点
    handleBegin() {
      if (!this.form.reagentTeamId) {
        this.$notify.warning('请选择试剂专业组')
        return
      }
      this.utils.loadShow()
      this.$ajax.post('/wm/tertiary_stock_check/save', this.form).then(resp => {
        if (!this.form.id) {
          this.$set(this.form, 'id', resp.data.id)
          this.$set(this.form, 'stockNum', resp.data.stockNum)
          this.$set(this.form, 'stockNormal', resp.data.stockNormal)
          this.$set(this.form, 'stockSurplus', resp.data.stockSurplus)
          this.$set(this.form, 'stockUnknown', resp.data.stockUnknown)
          this.$set(this.form, 'busKey', resp.data.busKey)
          this.$set(this.form, 'stockLoss', resp.data.stockLoss)
          this.$set(this.form, 'flagFinished', 0)
          this.utils.loadHide()
          this.reloadList()
          this.$nextTick(() => {
            this.$refs.scan.focus()
          })
        }
      })
    },

    //结束盘点
    handleEnd() {
      this.$dialog.confirm({
        message: '是否结束当前盘点?',
      }).then(() => {
        this.utils.loadShow()
        this.form.flagFinished = 1
        let checkItem = {
          id: this.form.id,
          warehouseId: this.form.warehouseId,
          flagFinished: this.form.flagFinished
        }
        this.$ajax.post('/wm/tertiary_stock_check/save', checkItem).then(response => {
          this.reload()
          this.utils.loadHide()
        })
      }).catch(() => {
        // on cancel
      })
    },

    //盘点类型选择后
    selectChange(item) {
      this.selectVisible = false
      this.form.checkType = item.value
      this.form.checkTypeName = item.label
    },

    //盘点类型显示名称
    setCheckType() {
      let findIndex = this.checkTypeList.findIndex(ob => ob.value == this.form.checkType)
      if (findIndex != -1) {
        this.form.checkTypeName = this.checkTypeList[findIndex].label
      }
    },

    //打开弹框
    open(type) {
      if (type == 'ReagentTeam') {
        let wrapper = this.$newWrapper().ne('name', this.form.reagentTeamName)
        this.$refs.listItemReagentTeam.setQueryWrapper(wrapper)
        this.$refs.listItemReagentTeam.show()
      } else  if (type == 'Matr') {
        let wrapper = this.$newWrapper().eq('base_type', 'reagent')
        this.$refs.listItemMatr.setQueryWrapper(wrapper)
        this.$refs.listItemMatr.show()
      }  else  if (type == 'checkType') { //盘点类型
        this.selectVisible = true
      } else {
        let wrapper = this.$newWrapper().eq('reagentTeamId', this.form.reagentTeamId).ne('flagFinished', 1)
        wrapper.orderConditions.push({ field: 'gmtCreate', rule: 'desc' })
        this.$refs.listItemStockCheck.setQueryWrapper(wrapper)
        this.$refs.listItemStockCheck.show()
      }
    },

    //试剂组选择
    changeReagentTeam(item) {
      this.$set(this.form, 'reagentTeamId', item.id)
      this.$set(this.form, 'reagentTeamName', item.name)
    },

    //试剂选择
    changeMatr(item) {
      this.$set(this.form, 'matrId', item.id)
      this.$set(this.form, 'matrName', item.name)
    },

    //盘点单选择
    changeStockCheck(item) {
      this.$set(this.form, 'id', item.id)
      this.$set(this.form, 'stockNum', item.stockNum)
      this.$set(this.form, 'stockNormal', item.stockNormal)
      this.$set(this.form, 'stockSurplus', item.stockSurplus)
      this.$set(this.form, 'stockUnknown', item.stockUnknown)
      this.$set(this.form, 'busKey', item.busKey)
      this.$set(this.form, 'stockLoss', item.stockLoss)
      this.$set(this.form, 'flagFinished', 0)
      this.$set(this.form, 'checkType', item.checkType)
      this.reloadList()
      this.utils.clearFocus(this, 'scan', 'scan')
      this.setCheckType()
    },

    //刷新选择
    reload(isByTop) {
      if (isByTop != true && this.form.flagFinished == 0) {
        this.$dialog.alert({
          title: '标题',
          message: '当前盘点任务尚未结束，请先结束!',
        }).then(() => {

        }).catch(() => {
        })
        return
      }
      this.form = {}
      this.form.stockNum = 0
      this.form.stockSurplus = 0
      this.form.stockUnknown = 0
      this.form.stockLoss = 0
      this.stocks = []
      const currentUser = this.$store.getters.currentUser.currentUser
      this.$set(this.form, 'deptId', currentUser.deptId)
      this.$set(this.form, 'deptName', currentUser.deptName)
      this.$set(this.form, 'warehouseId', this.utils.getCurrentWarehouse().warehouseId)
      this.$set(this.form, 'warehouseName', this.utils.getCurrentWarehouse().warehouseName)
      this.reloadList()
      if (this.strings.isBlank(this.form.warehouseId)) {
        Dialog.alert({
          title: '系统提示',
          message: '请先到工作台设置当前仓库，再进行操作',
        })
          .then(() => {
            this.$store.commit('SET_WORKBENCH_ROUTE', { name: 'dashboard' })
          })
      }
    },
    getCheckStatus(checkStatus) {
      return this.checkStatus.filter(ob => ob.key == checkStatus)[0]
    },
    showStock(item) {
      this.utils.loadShow()
      let params = {
        matrId: item.matrId,
        checkId: item.checkId,
        reagentTeamId: item.reagentTeamId
      }
      this.$ajax.get('/wm/tertiary_stock_check_item/getStockSumByMatr', { params }).then(response => {
        this.utils.loadHide()
        if (response.code == 0) {
          this.result = response.data
          this.visible = true
        } else {
          this.$notify.warning(response.msg)
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
  },
  mounted() {
    this.reload()
  }
}
</script>

<style lang="scss" scoped>
.van-col {
    text-align: center;
}
.popup {
    width: 60%;
    height: 100%;
}
.check-row {
    font-size: 18px;
    margin: 5px;
    .red {
    color: red;
    }
    .green {
    color: green;
    }
    .gray {
    color: gray;
    }
    .showRow {
      height: 20%;
      font-size: 18px;
    }
}
</style>
